<template>
  <button @click="print">打印</button>
  <div id="scrollBar">
    <div class="list-card">
      <div class="table-container">
        <div class="table-container">
          <table class="table-layout">
            <tbody>
              <tr v-for="item in 90" :key="item">
                <td class="table-cell">
                  这是第{{item}}行
                </td>
                <td class="table-cell" colspan="6">
                  这是右边
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// const print = () => {
//   const newDom = document.querySelector(".list-card").innerHTML;
//   const oldDom = document.body.innerHTML;
//   document.body.innerHTML = newDom;
//   window.print();
//   document.body.innerHTML = oldDom;
//   window.location.reload();
// }

const print = () => {
  const dom = document.querySelector("#scrollBar").outerHTML;
  const iframe = document.createElement("iframe");
  iframe.setAttribute("style", "position:absolute;width:0;height:0;top:-10px;left:-10px;");
  document.body.appendChild(iframe);

  const doc = iframe.contentDocument;
  
  doc.open();
  doc.write(getStyle() + dom);
  doc.close();

  iframe.onload = function () {
    iframe.contentWindow.print();

    setTimeout(() => {
      // document.body.removeChild(iframe);
    }, 100);
  };

  // 获取样式
  function getStyle() {
    const styles = document.getElementsByTagName("style");
    console.log('🚀 ~ getStyle ~ styles:', styles)
    let str = "";

    for (let i = 0; i < styles.length; i++) {
      str += styles[i].outerHTML;
    }

    return str;
  }
}

</script>

<style>
* {
  margin: 0;
  padding: 0;
}

body {
  background: #000000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.list-card {
  width: 900px;
  background: #ffffff;
  border-radius: 10px;
  margin: 20px 0;
  padding: 20px;
}
.table-layout {
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
}

.table-cell {
  display: table-cell;
  text-align: center;
  height: 60px;
  border: 1px solid #e4e4e4;
  color: #333333;
  font-size: 14px;
}

@page {
  /* size: auto; */
  margin: 20px 20px 0;
}
</style>
